<template>
    <div class="mainView">
        <div class="leftView" :class="{ 'hidden': leftHidden }">
            <ChatList
                @create-new-chat="createNewChat"
                @function-selected="selectFunction"
            />
            <UserCard
                :user-name="userName"
                @logout="logout"
            />
        </div>
        <div class="close-left" :class="{ 'hidden': leftHidden }" @click="closeLeft">
            <div v-if="leftHidden===false" class="tooltip">关闭侧栏</div>
            <div v-else class="tooltip">打开侧栏</div>
        </div>
        <div class="rightView">
            <div class="content">
                <NewProjectView v-if="currentFunction == 0" />
                <FunctionPointView v-else-if="currentFunction == 1" />
                <CKMetricsView v-else-if="currentFunction == 2" />
                <LKMetricsView v-else-if="currentFunction == 3" />
                <UseCaseMetricsView v-else-if="currentFunction == 4" />
                <div v-else class="welcome-message">
                    <h2>欢迎使用软件度量工具</h2>
                    <p>请从左侧选择要使用的功能模块</p>
                </div>
            </div>
            <!-- <FileUpload
                :selected-file-list="selectedFileList"
                @file-change="onFileChange"
                @remove-file="removeFile"
                @send-question="sendQuestion"
                @trigger-upload="triggerFileUpload"
            /> -->
        </div>
    </div>
    <el-dialog
        v-model="dialogVisible"
        title="警告"
        width="500"
        :before-close="handleClose"
        style="border-radius: 15px;background-color: #212121;">
        <span style="color: #a0a0a0;">您确定要删除此对话吗？请注意此操作不可逆！</span>
        <template #footer>
        <div class="dialog-footer">
            <el-button @click="deleteChat">取消</el-button>
            <el-button type="primary" @click="deleteChat()" style="background-color: red;border:none;">
            确定
            </el-button>
        </div>
        </template>
    </el-dialog>
</template>
<script>
import $ from 'jquery'
import {ref, watch, nextTick, onMounted} from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus';
import ChatList from '@/components/ChatList.vue'
import ChatMessage from '@/components/ChatMessage.vue'
import UserCard from '@/components/UserCard.vue'
import FileUpload from '@/components/FileUpload.vue'
import FunctionPointView from '@/components/FunctionPointView.vue'
import CKMetricsView from '@/components/CKMetricsView.vue'
import LKMetricsView from '@/components/LKMetricsView.vue'
import UseCaseMetricsView from '@/components/UseCaseMetricsView.vue'
import NewProjectView from '@/components/NewProjectView.vue'

export default {
    name: 'Main',
    components: {
        ChatList,
        ChatMessage,
        UserCard,
        FileUpload,
        FunctionPointView,
        CKMetricsView,
        LKMetricsView,
        UseCaseMetricsView,
        NewProjectView
    },
    data() {
        return {
            ifip:localStorage.getItem('ifip'),
            chatItems: [],
            messages:[],
            showMore: false,
            showOptions: false,
            leftHidden: false,
            activeChatId: null,
            isNull: true,
            isUserSetOpen: false,
            userIP:localStorage.getItem('ip'),
            userName: localStorage.getItem('username'),
            message: {},

            isClick: false,
            select_clicked : false,
            img_answer: '',
            editingChatId :null,
            dialogVisible:false,
            ipdialogVisible:true,
            stream:null,
            content: '',
            rows: 3,
            selectedFileList: [],
            isContentEmpty: true,
            currentFunction: null
        };
    },
    computed: {
        isChatItemActive() {
            return (chatId) => {
                return this.showMore && this.activeChatId === chatId;
            };
        },
        isContentEmpty() {
            return this.content.trim() === '';
        },

    },
    methods: {
        logout(){
            this.userName="用户名";
            this.$router.push('/');
        },
        async deleteChat() {
            this.dialogVisible = false
            for (var i = 0; i < this.chatItems.length; i++) {
                if (this.chatItems[i].chatId === this.activeChatId) {
                    this.chatItems.splice(i, 1)
                    break
                }
            }
            // 静态数据模拟删除成功
            console.log('删除chatid:', this.activeChatId)
            this.activeChatId = null

            // 后端请求（已注释）
            /*
            try {
                const response = await axios({
                    url: `http://127.0.0.1:8080/api/chat/${this.activeChatId}`,
                    method: 'DELETE',
                });
                console.log('删除chatid发送到后端:', response.data);
            } catch (error) {
                console.error('删除chatid到后端时出错:', error);
            }
            */
        },
        renamechat(chatId){
            this.editingChatId=chatId;
            this.closeOptions();
            this.$nextTick(() => {
                const inputs=$('.renamechat');
                inputs.focus();
                inputs.setSelectionRange(inputs.value.length, inputs.value.length);
            });
        },
        async finishRenaming(chatId, newName) {
            this.editingChatId = null
            console.log('重命名chatid:', chatId, '新名称:', newName)
            // 静态数据模拟重命名成功
            const chatItem = this.chatItems.find(item => item.chatId === chatId)
            if (chatItem) {
                chatItem.name = newName
            }

            // 后端请求（已注释）
            /*
            try {
                const response = await axios({
                    url: `http://127.0.0.1:8080/api/chat/${this.activeChatId}/name`,
                    method: 'POST',
                    data: { name: newName }
                });
                console.log('改对话标题发送到后端:', response.data);
            } catch (error) {
                console.error('改对话标题到后端时出错:', error);
            }
            */
        },
        userSet() {
            this.isUserSetOpen = !this.isUserSetOpen;
        },
        closeLeft() {
            this.leftHidden = !this.leftHidden;
            // 使用 nextTick 确保 DOM 更新后再触发窗口调整事件
            this.$nextTick(() => {
                window.dispatchEvent(new Event('resize'));
            });
        },
        newChat() {
            this.isNull = false
        },
        toggleHidden(chatId) {
            if (this.activeChatId !== chatId) {
                this.activeChatId = chatId;
                console.log(this.activeChatId);
                this.showMore = true;
                $('.chat-item').removeClass('bg-changed');
                $('.chat-item-more').hide();
                $('.chat-item-name').removeClass('hidden');
                $('.chat-item[data-chat-id="' + this.activeChatId + '"]').addClass('bg-changed').find('.chat-item-more').show();
                const activeElement = $('.chat-item[data-chat-id="' + this.activeChatId + '"]');
                activeElement.find('.chat-item-name').addClass('hidden');
                this.updateOptionsListPosition(activeElement);
                this.isNull = false;
                this.fetchChatItemInfo();
                this.scrollToBottom();
            }
        },
        updateOptionsListPosition(element) {
            const $element = $(element);
            const offset = $element.offset();
            const optionsList = $('.options-list');
            optionsList.css({
                top: offset.top
            })
        },
        toggleOptions(chatId) {
            this.showOptions = !this.showOptions;
            this.activeChatId = chatId;
        },
        closeOptions() {
            this.showOptions = false;
        },
        closeOptionsOutside(event) {
            if (!event.target.closest('.options-list')) {
                this.closeOptions();
            }
        },
        createNewChat() {
            this.messages = [];
            this.activeChatId = null;
            this.showMore = false;
            $('.chat-item').removeClass('bg-changed');
            this.isNull = true;
            this.currentFunction = 0; // 设置为新项目模块
            this.message = {};
            console.log(this.message);
        },
        scrollToBottom(){
            this.$nextTick(() => {
			    var scrollHeight = $('#chat_part').prop("scrollHeight");
                $('#chat_part').animate({scrollTop:scrollHeight}, 500);
		    })
        },
        selectModel(){
            this.select_clicked = !this.select_clicked
            console.log(this.select_clicked)
        },
        flow(){
            this.select_clicked = !this.select_clicked;
            this.outputModel = true;
            console.log(this.select_clicked)
            
        },
        block(){
            this.select_clicked = !this.select_clicked;
            this.outputModel = false;
            console.log(this.select_clicked)
            
        },

        //使用结构赋值进行异常处理
		promise_error_process(promise){
			return promise.then(data=>[null,data])
							.catch(err=>[err,null])
		},

        //获取对话列表
        async fetchChatItemsByAjax(){
            const response = await axios({
                url:        `http://127.0.0.1:8080/api/user/${this.userName}/chat`,
                method:     'GET',
            })
            return response
        },
        async fetchChatItems() {
            // 模拟数据
            this.chatItems = [
                {
                    chatId: 1,
                    name: "功能1"
                },
                {
                    chatId: 2,
                    name: "功能2"
                },
                {
                    chatId: 3,
                    name: "功能3"
                }
            ]

            // 后端请求（已注释）
            /*
            const [err, result] = await this.promise_error_process(this.fetchChatItemsByAjax())
            if (err) {
                console.log("获取对话列表失败")
            } else {
                console.log(result.data.data)
                this.chatItems = result.data.data
            }
            */
        },

        //获取对话记录
        async fetchChatItemInfoByAjax(){
            const response = await axios({
                url:        `http://127.0.0.1:8080/api/chat/${this.activeChatId}/dialog`,
                method:     'GET',
            })
            return response
        },
        async fetchChatItemInfo() {
            // 模拟数据
            this.messages = [{
                question: "这是一个示例问题",
                answer: "这是一个示例回答"
            }]
            this.message = this.messages[0]

            // 后端请求（已注释）
            /*
            const [err, result] = await this.promise_error_process(this.fetchChatItemInfoByAjax())
            if (err) {
                console.log("获取对话详情失败")
            } else {
                console.log(result.data.data)
                this.messages = result.data.data
                this.message = this.messages[0]
            }
            */
        },
        clickAdd(event){
            event.target.value = null
        },
        async uploadFile(formData) {
            console.log('上传文件:', [...formData])
            // 模拟上传成功
            this.message = {
                question: "已上传文件",
                answer: "文件分析结果示例"
            }
            this.selectedFileList = []
            this.fetchChatItems()

            // 后端请求（已注释）
            /*
            const response = await fetch(`http://127.0.0.1:8080/api/newChat/${this.userName}`, {
                method: "POST",
                body: formData,
            });
            console.log(response);
            const data = await response.json();
            this.message.question = data.data.chatName
            this.message.answer = data.data.newAnswer.text
            console.log("显示数据")
            console.log(this.message)
            console.log(data.data)
            this.selectedFileList = []
            this.fetchChatItems()
            */
        },
        async sendQuestion(content) {
            console.log('发送问题:', content)
            // 模拟发送成功
            this.message = {
                question: content,
                answer: "这是对问题的回答示例"
            }
            this.fetchChatItems()

            // 后端请求（已注释）
            /*
            const response = await fetch(`http://127.0.0.1:8080/api/chat/text/${this.userName}`, {
                method: "POST",
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ question: content })
            });
            const result = await response.json();
            console.log(result)
            this.message.question = result.data.chatName
            this.message.answer = result.data.newAnswer.text
            this.fetchChatItems()
            */
        },
        triggerFileUpload() {
            this.$refs.fileInput.click(); // 触发文件选择框
        },
        onFileChange(file) {
            // 检查文件是否已经存在
            const fileExists = this.selectedFileList.some(existingFile => 
                existingFile.name === file.name && 
                existingFile.size === file.size && 
                existingFile.lastModified === file.lastModified
            );
            if (!fileExists || this.selectedFileList.length === 0) {
                this.selectedFileList.push(file); // 如果文件不在数组中，则添加
            } else {
                console.log("文件已存在")
            }
        },
        removeFile(index){
            this.selectedFileList.splice(index,1)
        },
        selectFunction(funcId) {
            console.log(funcId);
            this.currentFunction = funcId;
            this.isNull = false;
            // 根据选择的功能加载相应的内容
            this.loadFunctionContent(funcId);
        },
        loadFunctionContent(funcId) {
            // 这里可以根据不同的功能加载不同的内容
            switch(funcId) {
                case 0:
                    this.message = { content: '新项目功能' };
                    break;
                case 1:
                    this.message = { content: '功能点度量功能' };
                    break;
                case 2:
                    this.message = { content: 'CK度量功能' };
                    break;
                case 3:
                    this.message = { content: 'LK度量功能' };
                    break;
                case 4:
                    this.message = { content: '用例图度量功能' };
                    break;
            }
        },
    },

    
    mounted() {
        document.addEventListener('click', this.closeOptionsOutside);
        $('.flex-col').on('scroll', ()=> {
            if (this.activeChatId) {
            const activeElement = $('.chat-item[data-chat-id="' + this.activeChatId + '"]');
            this.updateOptionsListPosition(activeElement);
          }
        });
        
    },
    created() {
        this.fetchChatItems();
        if(this.ifip === '0')
            this.ipdialogVisible = true
        else this.ipdialogVisible = false
        this.currentFunction = 0; // 设置默认功能为新项目
    },
    setup (props, {emit}) {
        const textareaRef = ref(null);
        const rows = ref(1)
        const content = ref('')

        onMounted(() => {
            nextTick(adjustTextareaSize);
        });

        watch(() => content.value, () => {
            nextTick(adjustTextareaSize);
        })

        // 参考vant组件库中的field组件
        const adjustTextareaSize = () => {
            let textarea = textareaRef.value
    
            textarea.style.height = 'auto'; 
            const height = textarea.scrollHeight;

            if (height) { // 改变textarea高度达到自适应
                textarea.style.height = height + "px";
            }
        }
        return {
            textareaRef,
            rows,
            content
        }
    }
}
</script>
<style>
.el-dialog__title{
    color: #b0b0b0;
}
</style>
<style scoped>
  .main-part {
            display: flex;
            flex-direction: column; /* 垂直排布 */
            width: 1100px; /* 宽度占满父容器 */
            height: 80vh; 
        }

        .question-up, .answer-up {
            overflow-y: auto; /* 只显示竖直滚动条 */
            width: 100%; 
            word-wrap: break-word; /* 当单词超出容器宽度时自动换行 */
            overflow-wrap: break-word; /* 同样用于处理单词换行 */
            border-radius: 10px;
            margin-bottom: 10px;
        }
        .word1{
            color: #000000;
        }

        .question-up {
            flex: 64; /* 占比64 */
            background-color: #2f2f2f;
            height: 0vh;
            margin-top: 20px
        }

        .answer-up {
            flex:36;
            background-color: #2f2f2f;
            /* border: 1.2px solid rgb(228, 224, 224); */
        }
.mainView {
    position: relative;
    display: flex;
    height: 100%;
    overflow: hidden;
    background-color: #ffffff;
    width: 100%;
}
.selectedFileList{
    display: flex;

    
}
.close-left {
    position: absolute;
    z-index: 100;
    left: 265px;
    top: 50%;
    height: 40px;
    width: 8px;
    background-color: #409eff;
    border-radius: 4px;
    cursor: pointer;
    transition: transform 1s ease-in-out, background-color 0.3s ease-in-out;
}

.close-left.hidden {
    transform: translateX(-255px);
}

.close-left:hover {
    background-color: #66b1ff;
}

.close-left .tooltip {
    visibility: hidden;
    width: 80px;
   
    color: #333333;
    text-align: center;
    border-radius: 10px;
    padding: 5px 0;
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    opacity: 0;
    transition: opacity 0.3s ease-in-out;
    white-space: nowrap;
}

.close-left:hover .tooltip {
    visibility: visible;
    opacity: 1;
}

.leftView {
    display: flex;
    flex-direction: column;
    width: 250px;
    background-color: #ffffff;
    padding: 12px;
    padding-right: 5px;
    transition: transform 1s ease-in-out, width 1s ease-in-out;
    border-right: 1px solid #e4e7ed;
    flex-shrink: 0; /* 防止侧栏被压缩 */
}

.leftView.hidden {
    transform: translateX(-274px);
    width: 0px;
    margin: 12px 0;
}

.flex-col {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    max-height: 100%;
    max-width: 250px;
    overflow-y: auto;
    overflow-x: visible;
}

::-webkit-scrollbar {
    visibility: hidden;
    width: 5px;
    background-color: black;
}

::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
    background-color: #555;
}

.time-tag {
    padding: 10px;
    font-size: 15px;
    margin-top: 10px;
    color: #ccc;
}

.new-chat {
    padding: 5px;
    height: 40px;
    display: flex;
    align-items: center;
    border-radius: 10px;
}

.fa-magnifying-glass {
    font-size: 20px;
    padding-left: 8px;
}

.new-chat-title {
    flex: 1;
    padding-left: 10px;
}

.chat-item {
    padding: 10px;
    margin: 3px 0;
    height: 35px;
    display: flex;
    align-items: center;
    border-radius: 10px;
    position: relative;
}

.chat-item.bg-changed {
    background-color: #212121;
}
.selectedFileList-in{
    margin-top: 10px;
    width: 260px;
    height: 60px;
    background-color: #171717;
    margin-right: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 20px;

}
.selectedFileList-in-border{
    width: 90%;
    height: 50px;
    display: flex;
    align-items: center;
    /* background-color: #000000; */
}
.file-img{
    margin-left: 10px;
    width: 40px;
    height: 40px;
    background-color: #244a96;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
}
.file-name{
    width: 80px;
    margin-left: 10px;
    display: flex;
    flex-direction: column;
}
.chat-item:hover {
    background-color: #212121;
    cursor: pointer;
    transition: 0.3s;
}
.renamechat{
    background-color: transparent;
    outline: none;
    border: none;
    color: white;
    font-size: 15px;
}
.chat-item-name {
    background-color: transparent;
    color: white;
    outline: none;
    width: 100%;
    white-space: nowrap;
    overflow: hidden;
    mask-image: linear-gradient(to right, black 80%, transparent 100%);
    -webkit-mask-image: linear-gradient(to right, black 80%, transparent 100%);
}

.chat-item-name.hidden {
    mask-image: linear-gradient(to right, black calc(100% - 60px), transparent 90%);
    -webkit-mask-image: linear-gradient(to right, black calc(100% - 60px), transparent 90%);
}

.chat-item-more {
    z-index: 10;
    right: 10px;
    top: 0;
    bottom: 0;
    position: absolute;
    width: 60px;
    display: flex;
    flex-direction: row-reverse;
    align-items: center;
}

.chat-item-more.show {
    visibility: hidden;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.3s ease;
}

.fade-enter,
.fade-leave-to {
    opacity: 0;
}

.options-list {
    position: absolute;
    left:250px;
    top: 0;
    background-color: #2f2f2f;
    border: 1px solid #444444;
    border-radius: 10px;
    padding: 8px;
    z-index: 1000;
}

.options-list ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

.options-list li {
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 8px;
}

.options-list li:hover {
    background-color: #424242;
}

.user-card {
    margin-top: 10px;
    position: relative;
}

.user-setting {
    position: absolute;
    top: -90px;
    left:0 px;
    width: 220px;
    height: 90px;
    background-color: #201e1e;
    border: 1px solid #464242;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    padding: 10px;
}

.setting-item {
    font-size: 18px;
    margin-top: 10px;
    border-bottom: #555 1px solid;
    padding-bottom: 10px;
    padding-left: 10px;
}

.setting-item:first-child{
    margin-top: 0;
}
.setting-item:last-child {
    border-bottom: 0px;
    padding-bottom: 0;
}

.rightView {
    flex: 1;
    display: flex;
    flex-direction: column;
    background-color: #ffffff;
    padding: 20px;
    width: calc(100% - 250px);
    transition: width 1s ease-in-out;
    overflow-x: hidden;
}

.leftView.hidden + .rightView {
    width: 100%;
}
/* 
.select_inputModel {
    width: 135px;
    height: 55px;
    margin-top: 10px;
    text-align: center;
    position: relative;
    font-size: 18px;
    padding-left: 15px;
} */
.selectView{
    position: absolute;
    bottom: -105px;
    left:-2px;
    width: 173px;
    height: 100px;
    background-color: #201e1e;
    border: 1px solid #464242;
    border-radius: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}
.option_model{
    width : 150px;
    margin: 10px;
    padding : 5px 0;
    border-radius: 8px;
}
.option_model:hover{
    background-color: gray;
}
.option_name{
    margin-left: 10px;
}
.null {
    text-align: center;
    margin-top: 150px;
}

.chat_part {
    overflow-y: auto;
    font-size: 18px;
    min-width: max(60%,500px);
    max-width: 100%;
    height: 100%;

}
.chat_part::-webkit-scrollbar {
  	display: none;
}
.chat_part_con{
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
}
.ai_tool {
    text-align: left;
    margin-top: 30px;
    margin-left: 50px;
    display: flex;
}

.ai_head {
    border-radius: 50%;
    width: 40px;
    height: 40px;
}

.icon_ai {
    margin-right: 20px;
    margin-top: 10px;
}

.icon_user {
    margin-left: 20px;
}

.user {
    text-align: right;
    display: flex;
    justify-content: flex-end;
    margin-top: 30px;
    margin-right: 50px;
}

.user_head {
    border-radius: 50%;
    width: 40px;
    height: 40px;
}
.msg_content{
    white-space:pre-line;
    word-wrap: break-word;
    margin-top: 8px;
    padding: 10px;
    min-width: 50px;
    border-radius: 15px;
    text-align: left;
}
.identify {
    font-size: 12px;
}

.question {
    display: flex;
    flex-direction: column;
    width: 100%;
    color: #fff;
    align-items: center;
    justify-content: center;
}
.upLoadFile{
    width: 55%;
    margin-bottom: 5px;
    display: flex;
}
.upLoadBtn{
    border:1px solid #fff;
    background-color: rgb(61, 60, 60);
    color: #fff;
    min-width: 60px;
    max-height: 20px;
    padding: 3px;
    font-size: 12px;
    border-radius: 10px;
    margin-right: 10px;
}
.contain_chat{
    display: flex;
    flex-direction: column;
    margin: 0 auto;
    width: 60%;
    min-height: 50px;
    max-height: 215px;
    border-radius: 30px;
    border-style: solid;
    border: 1px solid #2f2f2f;
    background-color: #2f2f2f;
    padding: 5px;
    padding-left: 15px;
}


.others{
    display: flex;
}
.contain_chat:focus-within {
    box-shadow: 0 0 10px rgba(141, 141, 147, 0.5); 
}
.chat_input{
    flex:1;
    min-height: 20px;
    max-height: 200px;
    resize: none;
    font-size: 18px;
    border-radius: 18px;
    border: 0;
    outline:none;
    background-color: transparent;
    color:#ccc;
    padding:10px;
    margin-right: 10px;
}
.sendQuestion{
    display: flex;
    flex-direction: column-reverse;
    padding-right: 5px;
    padding-bottom: 5px;
}
.sendQuestion i.enabled {
    color: #fff; 
}
.sendQuestion i.disabled{
    color: #a0a0a0; 
}
.sendQuestion i:hover{
    color: #d0d0d0; 
}
</style>